package com.cli.springboottemplateengine.engine;

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import org.springframework.stereotype.Component;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

@Component
public class MustacheTemplateEngine implements TemplateEngine {

    private final MustacheFactory mustacheFactory;

    public MustacheTemplateEngine() {
        this.mustacheFactory = new DefaultMustacheFactory();
    }

    @Override
    public String doRender(String templateContent, Map<String, Object> model) {
        try {
            Mustache mustache = mustacheFactory.compile(new StringReader(templateContent), "template");
            StringWriter writer = new StringWriter();
            mustache.execute(writer, model).flush();
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException("Mustache 渲染失败", e);
        }
    }

    @Override
    public String getType() {
        return "mustache";
    }
}

